﻿using System;
using System.Windows.Data;
using System.Windows.Controls;
using System.Globalization;

namespace IBoLT.Validation
{

	public class IntRule : ValidationRule
	{
		private int _min;
		private int _max;

		public IntRule()
		{
		}

		public int Min
		{
			get { return _min; }
			set { _min = value; }
		}

		public int Max
		{
			get { return _max; }
			set { _max = value; }
		}

		public override ValidationResult Validate(object value, CultureInfo cultureInfo)
		{
			int res = 0;

			try
			{
				if (((string)value).Length > 0)
					res = Int32.Parse((String)value);
			}
			catch (Exception e)
			{
				return new ValidationResult(false, "Недопустимый символ или " + e.Message);
			}

			if ((res < Min) || (res > Max))
			{
				return new ValidationResult(false, "Введите число из диапозона: " + Min + " - " + Max + ".");
			}
			else
			{
				return new ValidationResult(true, null);
			}
		}
	}

	public class DoubleRule : ValidationRule
	{
		private Double _min;
		private Double _max;

		public DoubleRule()
		{
		}

		public Double Min
		{
			get { return _min; }
			set { _min = value; }
		}

		public Double Max
		{
			get { return _max; }
			set { _max = value; }
		}

		public override ValidationResult Validate(object value, CultureInfo cultureInfo)
		{
			Double res = 0;

			try
			{
				if (((string)value).Length > 0)
					res = Double.Parse((String)value);
			}
			catch (Exception e)
			{
				return new ValidationResult(false, "Недопустимый символ или " + e.Message);
			}

			if ((res < Min) || (res > Max))
			{
				return new ValidationResult(false, "Введите число из диапозона: " + Min + " - " + Max + ".");
			}
			else
			{
				return new ValidationResult(true, null);
			}
		}
	}

	public class DoubleToIntConverter : IValueConverter
	{
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return (int)(double)value;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return System.Convert.ToDouble((String)value);
		}
	}
}